#include "../Include/data_input.h"
#include "../Include/student_pub.h"
#include "../Include/course_pub.h"
#include "../Include/log_pub.h"  
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 清理输入缓冲区
void clear_input_buffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

// 从文件加载数据（student.txt和course.txt）
void load_data(StudentList s_head, CourseList c_head) {
    // 清空原有学生数据
    StudentNode *stu_temp = s_head->next;
    while (stu_temp) {
        StudentNode *del = stu_temp;
        stu_temp = stu_temp->next;
        free(del);
    }
    s_head->next = NULL;

    // 加载学生数据
    FILE *fp = fopen("student.txt", "r");
    if (fp) {
        StudentNode *new_stu;
        char id[20], name[50], course_ids[200];
        int total_credit;
        int count = 0;
        char line[512];

        while (fgets(line, sizeof(line), fp)) {
            // 跳过空行和注释行
            if (line[0] == '\n' || line[0] == '#' || line[0] == ' ') continue;

            // 解析格式：学号 姓名 总学分 [课程ID]
            int parsed = sscanf(line, "%s %s %d %[^\n]", id, name, &total_credit, course_ids);
            if (parsed >= 3) {
                if (parsed == 3) course_ids[0] = '\0';  // 无课程时设为空

                new_stu = malloc(sizeof(StudentNode));
                if (!new_stu) break;
                
                strcpy(new_stu->id, id);
                strcpy(new_stu->name, name);
                new_stu->total_credit = total_credit;
                strcpy(new_stu->course_ids, course_ids);
                new_stu->next = NULL;

                // 插入链表尾部
                StudentNode *p = s_head;
                while (p->next) p = p->next;
                p->next = new_stu;
                count++;
            }
        }
        fclose(fp);
        printf("学生数据加载完成，共%d条记录！\n", count);
    } else {
        perror("学生数据文件打开失败");
        printf("将创建新的学生数据文件\n");
    }

    // 清空原有课程数据
    CourseNode *course_temp = c_head->next;
    while (course_temp) {
        CourseNode *del = course_temp;
        course_temp = course_temp->next;
        free(del);
    }
    c_head->next = NULL;

    // 加载课程数据
    fp = fopen("course.txt", "r");
    if (fp) {
        CourseNode *new_course;
        char id[20], name[50], type[20];
        int hours, credit, selected, max;
        int count = 0;

        while (fscanf(fp, "%s %s %s %d %d %d %d", 
               id, name, type, &hours, &credit, &selected, &max) == 7) {
            new_course = malloc(sizeof(CourseNode));
            if (!new_course) break;
            
            strcpy(new_course->id, id);
            strcpy(new_course->name, name);
            strcpy(new_course->type, type);
            new_course->hours = hours;
            new_course->credit = credit;
            new_course->selected = selected;
            new_course->max = max;
            new_course->next = NULL;

            // 插入链表尾部
            CourseNode *p = c_head;
            while (p->next) p = p->next;
            p->next = new_course;
            count++;
        }
        fclose(fp);
        printf("课程数据加载完成，共%d条记录！\n", count);
    } else {
        perror("课程数据文件打开失败");
        printf("将创建新的课程数据文件\n");
    }
    write_log("数据加载完成");  
}

// 命令行录入初始数据
void input_data_cmd(StudentList s_head, CourseList c_head) {
    int stu_num, course_num;

    // 录入学生
    printf("请输入初始学生数量：");
    scanf("%d", &stu_num);
    clear_input_buffer();

    for (int i = 0; i < stu_num; i++) {
        StudentNode *new_stu = (StudentNode*)malloc(sizeof(StudentNode));
        printf("\n第%d个学生：\n", i+1);
        printf("学号：");
        scanf("%s", new_stu->id);
        printf("姓名：");
        scanf("%s", new_stu->name);
        new_stu->total_credit = 0;
        new_stu->course_ids[0] = '\0';  // 初始化选课记录为空
        new_stu->next = NULL;

        // 插入链表
        StudentNode *p = s_head;
        while (p->next) p = p->next;
        p->next = new_stu;
    }

    // 录入课程
    printf("\n请输入初始课程数量：");
    scanf("%d", &course_num);
    clear_input_buffer();

    for (int i = 0; i < course_num; i++) {
        CourseNode *new_course = (CourseNode*)malloc(sizeof(CourseNode));
        printf("\n第%d个课程：\n", i+1);
        printf("编号：");
        scanf("%s", new_course->id);
        printf("名称：");
        scanf("%s", new_course->name);
        printf("性质（必修/选修）：");
        scanf("%s", new_course->type);
        printf("学时：");
        scanf("%d", &new_course->hours);
        printf("学分：");
        scanf("%d", &new_course->credit);
        printf("人数上限：");
        scanf("%d", &new_course->max);
        new_course->selected = 0;
        new_course->next = NULL;

        // 插入链表
        CourseNode *p = c_head;
        while (p->next) p = p->next;
        p->next = new_course;
    }

    printf("初始数据录入完成！\n");
    write_log("命令行录入初始数据完成");
    save_data(s_head, c_head);
}

// 保存数据到文件
void save_data(StudentList s_head, CourseList c_head) {
    // 保存学生数据
    if (s_head) {
        FILE *fp = fopen("student.txt", "w");
        if (fp) {
            StudentNode *p = s_head->next;
            while (p) {
        
                fprintf(fp, "%s %s %d %s\n", 
                        p->id, p->name, p->total_credit, p->course_ids);
                p = p->next;
            }
            fclose(fp);
        } else {
            perror("学生数据保存失败");
        }
    }

    // 保存课程数据
    if (c_head) {
        FILE *fp = fopen("course.txt", "w");
        if (fp) {
            CourseNode *p = c_head->next;
            while (p) {
                fprintf(fp, "%s %s %s %d %d %d %d\n",
                       p->id, p->name, p->type, p->hours,
                       p->credit, p->selected, p->max);
                p = p->next;
            }
            fclose(fp);
        } else {
            perror("课程数据保存失败");
        }
    }
    write_log("数据保存完成");
}
